//
//  MovieViewController.m
//  WisdomZhuHai
//
//  Created by Ryan on 14-12-3.
//  Copyright (c) 2014 wyd. All rights reserved.
//

#import "MovieViewController.h"
#import "HotRateView.h"
#import "MovieDetailViewController.h"
#import "SingleMovieDetailViewController.h"
#import "MoreMovieViewController.h"

//static const CGSize CATEGORYVIEW_SIZE = {52,82};
static const CGFloat TITLECELL_HEIGHT = 85;
//static const CGSize HOTRECOMMENDVIEW_SIZE = {147, 147};
static const CGFloat MOVIELISTCELL_HEIGHT = 200;

@interface MovieViewController ()

@property (nonatomic,strong) UIView* headerView;
@property (nonatomic,strong) UIView* headerPopupView;

@property (nonatomic,assign) int currentIndex;
@property (nonatomic,strong) NSMutableArray* cinemaList;
@property (nonatomic,strong) NSDictionary* hotMovieList;
@property (nonatomic,strong) NSArray* areaList;

@end

static const CGFloat HEADER_BUTTON_HEIGHT = 34.f;

@implementation MovieViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.currentIndex = -1;
    
    self.areaList = @[@"香洲区", @"拱北区", @"斗门区", @"金湾区", @"高新区", @"横琴新区"];
    [self setupHeaderView];
    
    self.tableView.backgroundColor = [Common colorWithRGB:0xffffff];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //    [self setEnableRefresh:YES];
    self.pullTableViewDelegate = self;
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.tableView.bounds.size.width, 0.f)];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.tableView.bounds.size.width, 0.f)];
    self.title = @"电影院";
    [self getCinemaList];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)onClickArea:(id)sender
{
    NSLog(@"onClickArea");
    if (self.headerPopupView.hidden) {
        [self showHeaderPopupView];
    }
    else {
        [self hideHeaderPopupView];
    }
}

- (void)onClickNearby:(id)sender
{
    NSLog(@"onClickNearby");
}

- (void)onClickAreaCategory:(UIButton*)sender
{
    NSLog(@"onClickAreaCategory %@", sender.titleLabel.text);
    if ([self.area isEqualToString:sender.titleLabel.text]) {
        return;
    }
    self.area = sender.titleLabel.text;
    [self getCinemaList];
}

- (void)onTapHeaderPopupView:(UIGestureRecognizer*)gesture
{
    NSLog(@"onTapHeaderPopupView");
    [self hideHeaderPopupView];
}

#pragma mark - Protocol request
- (void)getCinemaList
{
    [[ProtocolManager shareInstance] getStoresList:self.type returnCount:STORE_LIST_RETURN_COUNT beginNo:self.currentIndex+1 area:self.area star:nil storeType:@"电影院" target:self selector:@selector(getCinemaCallback:)];
}

#pragma mark - Protocol call back
- (void)getCinemaCallback:(NSDictionary*)dic
{
    NSLog(@"getCinemaCallback %@",dic);
    if (dic == nil) {
        //[self resetPullTableViewState];
        return;
    }
    if (self.currentIndex == -1) {
        self.cinemaList = [NSMutableArray array];
    }
    NSArray* cinemaList = [Common valueForKey:P_CINEMAS dic:dic];
    NSDictionary* hotMovieList = [Common valueForKey:P_MOVIES dic:dic];
    if ([cinemaList isKindOfClass:[NSArray class]]) {
        [self.cinemaList addObjectsFromArray:cinemaList];
        self.currentIndex += self.cinemaList.count;
    }
    if ([hotMovieList isKindOfClass:[NSArray class]]) {
        self.hotMovieList = hotMovieList;
    }
//    if (cinemaList.count < STORE_LIST_RETURN_COUNT) {
//        [self setEnableLoadMore:NO];
//    }
//    else {
//        [self setEnableLoadMore:YES];
//    }
    //[self resetPullTableViewState];
    [self.tableView reloadData];
}

#pragma mark - Private
- (void)setupHeaderView
{
    UIView* view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 40)];
    view.backgroundColor = [UIColor colorWithWhite:0.92 alpha:1];
    [self.view addSubview:view];
    view.layer.borderWidth = 0.5;
    view.layer.borderColor = [UIColor grayColor].CGColor;
    self.headerView = view;
    
    UIButton* btnArea = [self createHeaderButton:@"区域" selector:@selector(onClickArea:)];
    CGRect frame = btnArea.frame;
    frame.size.width = self.view.bounds.size.width;
    //    btnArea.center = CGPointMake(view.bounds.size.width/2, view.bounds.size.height/2);
    [view addSubview:btnArea];
    
    //    UIButton* btnNearby = [self createHeaderButton:@"附近" selector:@selector(onClickNearby:)];
    //    btnNearby.center = CGPointMake(view.bounds.size.width*3/4, view.bounds.size.height/2);
    //    [view addSubview:btnNearby];
    
    //    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(view.bounds.size.width/2-0.5, 11, 1, view.bounds.size.height - 20)];
    //    line.backgroundColor = [UIColor darkGrayColor];
    //    [view addSubview:line];
    
    [self setupHeaderPopupView];
}

- (void)setupHeaderPopupView
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, self.headerView.bounds.size.height, self.view.bounds.size.width, self.view.bounds.size.height - self.headerView.bounds.size.height)];
    view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4];
    [self.view insertSubview:view belowSubview:self.headerView];
    view.hidden = YES;
    self.headerPopupView = view;
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapHeaderPopupView:)];
    tapGesture.cancelsTouchesInView = NO;
    [view addGestureRecognizer:tapGesture];
    
    UIView *btnView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, HEADER_BUTTON_HEIGHT*self.areaList.count+0.5*(self.areaList.count-1))];
    btnView.backgroundColor = self.headerView.backgroundColor;
    btnView.tag = 1000;
    btnView.layer.borderWidth = 0.5;
    btnView.layer.borderColor = [UIColor darkGrayColor].CGColor;
    [view addSubview:btnView];
    
    CGFloat y = 0;
    for (int i=0; i<self.areaList.count; i++) {
        UIButton *btn = [self createHeaderButton:self.areaList[i] selector:@selector(onClickAreaCategory:)];
        CGRect frame = btn.frame;
        frame.origin.y = y;
        btn.frame = frame;
        [btnView addSubview:btn];
        
        y += HEADER_BUTTON_HEIGHT;
        if (i < self.areaList.count-1) {
            UIView *line = [[UIView alloc] initWithFrame:CGRectMake(8, y, btnView.bounds.size.width - 16, 0.5)];
            line.backgroundColor = [UIColor grayColor];
            [btnView addSubview:line];
            y += 0.5;
        }
    }
}

- (UIButton*)createHeaderButton:(NSString*)title selector:(SEL)selector
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, self.headerView.bounds.size.width, HEADER_BUTTON_HEIGHT);
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn addTarget:self action:selector forControlEvents:UIControlEventTouchDown];
    btn.titleLabel.font = [UIFont systemFontOfSize:15];
    
    return btn;
}

- (void)showHeaderPopupView
{
    self.headerPopupView.hidden = NO;
    UIView *btnView = [self.headerPopupView viewWithTag:1000];
    btnView.center = CGPointMake(btnView.bounds.size.width/2, -btnView.bounds.size.height/2);
    [UIView animateWithDuration:0.3 animations:^{
        btnView.center = CGPointMake(btnView.bounds.size.width/2, btnView.bounds.size.height/2);
    } completion:^(BOOL finished){
        
    }];
}

- (void)hideHeaderPopupView
{
    UIView *btnView = [self.headerPopupView viewWithTag:1000];
    [UIView animateWithDuration:0.3 animations:^{
        btnView.center = CGPointMake(btnView.bounds.size.width/2, -btnView.bounds.size.height/2);
    } completion:^(BOOL finished){
        self.headerPopupView.hidden = YES;
    }];
}


#pragma mark - Cell
//加载cell数据
- (void)loadCellData:(UITableViewCell*)cell index:(int)index
{
    if (index >= self.cinemaList.count) {
        return;
    }
    NSDictionary* cellData = self.cinemaList[index];
    NSString *name = [Common valueForKey:P_NAME dic:cellData];
    UILabel *lbName = (UILabel*)[cell viewWithTag:1001];
    lbName.text = name;
    [lbName sizeToFit];
    CGRect nameframe = lbName.frame;
    nameframe.size.width = MIN(nameframe.size.width, 270);
    lbName.frame = nameframe;
    
    CGFloat star = [[Common valueForKey:P_RATE dic:cellData] floatValue]/2;
    HotRateView *hotView = [[HotRateView alloc] initWithHotRate:star];
    CGRect frame = hotView.frame;
    frame.origin.x = 45;
    frame.origin.y = (cell.bounds.size.height - hotView.bounds.size.height)/2+2;
    hotView.frame = frame;
    if ([cell viewWithTag:1006] != nil) {
        [[cell viewWithTag:1006] removeFromSuperview];
    }
    UIImageView *moviePic = [[UIImageView alloc] initWithFrame:CGRectMake(lbName.frame.size.width+20,10.0,20,20)];
    moviePic.tag = 1006;
    moviePic.image = [UIImage imageNamed:@"movie/movie_groupon.png"];
    [cell addSubview:moviePic];
    [cell addSubview:hotView];

    
    NSString *address = [Common valueForKey:P_ADRESS dic:cellData];
    UILabel *lbAdress = (UILabel*)[cell viewWithTag:1003];
    lbAdress.text = address;
    NSString *price = [Common valueForKey:P_BASE_PRICE dic:cellData];
    UILabel *lbPrice = (UILabel*)[cell viewWithTag:1004];
    lbPrice.text = price;
    
}

//设置scrollview
- (void)setupScrollViewCell:(UITableViewCell*)cell
{
    if (self.hotMovieList == nil) {
        return;
    }
    UIScrollView *MovieScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, MOVIELISTCELL_HEIGHT)];
    int originX = 0;
    int i = 0;
    for(NSDictionary *movie in self.hotMovieList)
    {
        if (i < 5){
            //获取字段数据
            NSString *imgUrl = [Common valueForKey:P_COVER dic:movie];
            NSString *movieName = [Common valueForKey:P_NAME dic:movie];
            NSString *movieRate = [Common valueForKey:P_RATING dic:movie];
            int movieId = [[Common valueForKey:P_ID dic:movie] intValue];
            //view的点击事件回调
            UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapMovieView:)];
            //构图
            UIView *movieView = [[UIView alloc] initWithFrame:CGRectMake(originX+10, 10, 110, 180)];
            UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 125, 100, 50)];
            UILabel *ratingLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 145, 100, 50)];
            movieView.tag = movieId;
            nameLabel.font = [UIFont fontWithName:@"Helvetica" size:15.0];
            nameLabel.text = movieName;
            ratingLabel.font = [UIFont fontWithName:@"Helvetica" size:15.0];
            ratingLabel.textColor = [Common colorWithRGB:0xd3b322];
            ratingLabel.text = [NSString stringWithFormat:@"%@分", movieRate];
            UIImageView *scrollImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 135)];
            [scrollImage setImageWithURL:[Common getFullDownloadPathByRelativePath:imgUrl]];
            [movieView addGestureRecognizer:tapGesture];
            [movieView addSubview:scrollImage];
            [movieView addSubview:nameLabel];
            [movieView addSubview:ratingLabel];
            [MovieScroll addSubview:movieView];
            originX += 110;
            i++;
        }
    }
    UIView *moreView = [[UIView alloc] initWithFrame:CGRectMake(originX+10, 10, 200, 135)];
    moreView.backgroundColor = [Common colorWithRGB:0x999999];
    UILabel *moreLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 30, 135)];
    moreView.layer.cornerRadius = 3.0;
    //自动折行设置
    moreLabel.lineBreakMode = UILineBreakModeWordWrap;
    moreLabel.numberOfLines = 0;
    moreLabel.text = @"更多影片";
    //view的点击事件回调
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapMovieView:)];
    moreView.tag = -1;
    [moreView addGestureRecognizer:tapGesture];
    [moreView addSubview:moreLabel];
    [MovieScroll addSubview:moreView];
    
    [MovieScroll setContentSize:CGSizeMake(originX+50, MOVIELISTCELL_HEIGHT)];
    [cell.contentView addSubview:MovieScroll];
    [self scrollVIewCellConfig:MovieScroll];
}

//点击事件
- (void)onTapMovieView:(UITapGestureRecognizer*)gesture
{
    NSLog(@"onTapMovieView %d", gesture.view.tag);
    if (gesture.view.tag == -1) {
        MoreMovieViewController *MoreMovieViewCtrl = [[MoreMovieViewController alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        MoreMovieViewCtrl.type = self.type;
        [self.navigationController pushViewController:MoreMovieViewCtrl animated:YES];
    }
    else {
        SingleMovieDetailViewController *SingleMovieDetailViewCtrl = [[SingleMovieDetailViewController alloc] initWithFrame:[Common shareInstance].contentFrameNoTabBar style:UITableViewStylePlain];
        SingleMovieDetailViewCtrl.goodId = gesture.view.tag;
        [self.navigationController pushViewController:SingleMovieDetailViewCtrl animated:YES];
    }
}

- (void)scrollVIewCellConfig:(UIScrollView*)MovieScroll
{
    //设置委托
    MovieScroll.delegate = self;
    //设置背景颜色
    MovieScroll.backgroundColor = [Common colorWithRGB:0xDEDEDE];
    //设置取消触摸
    MovieScroll.canCancelContentTouches = NO;
    //设置滚动条类型
    MovieScroll.indicatorStyle = UIScrollViewIndicatorStyleWhite;
    //是否自动裁切超出部分
    MovieScroll.clipsToBounds = YES;
    //控制控件是否能滚动
    MovieScroll.scrollEnabled = YES;
    //设置是否可以进行画面切换
    MovieScroll.pagingEnabled = NO;
    //设置在拖拽的时候是否锁定其在水平或者垂直的方向
    MovieScroll.directionalLockEnabled = NO;
    //隐藏滚动条设置（水平、跟垂直方向）
    MovieScroll.alwaysBounceHorizontal = NO;
    MovieScroll.alwaysBounceVertical = NO;
    MovieScroll.showsHorizontalScrollIndicator = NO;
    MovieScroll.showsVerticalScrollIndicator = NO;
    
    MovieScroll.canCancelContentTouches = YES;
    MovieScroll.delaysContentTouches = YES;
}

#pragma mark - Table view data source
//返回table中有多少个组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 3;
}

//返回table中一个组有多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else if (section == 1){
        return 1;
    }
    return self.cinemaList.count;
}

//用cellForRowAtIndexPath来得到一个包含每一行显示信息的UITableViewCell对象.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    switch (indexPath.section) {
        case 0:
        {
            
            cell = [tableView dequeueReusableCellWithIdentifier:@"TitleCell"];
            // Configure the cell...
            if(cell == nil)
            {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TitleCell"];
            }
            UILabel *label = [ [ UILabel alloc ] initWithFrame: CGRectMake(10.0, 40.0, 100.0, 50.0) ];
            label.text = @"热映影片";
            label.textAlignment = UITextAlignmentLeft;
            label.textColor = [ UIColor blackColor ];
            label.font = [ UIFont fontWithName: @"Arial" size: 17.0 ];
            [cell addSubview:label];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            break;
        }
        case 1:
        {
            cell = [tableView dequeueReusableCellWithIdentifier:@"MovieScrollCell"];
            // Configure the cell...
            if(cell == nil)
            {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MovieScrollCell"];
            }
            [self setupScrollViewCell:cell];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            break;
        }
        case 2:
        {
            cell = [tableView dequeueReusableCellWithIdentifier:@"CinemaListCell"];
            // Configure the cell...
            if(cell == nil)
            {
                cell = [[NSBundle mainBundle] loadNibNamed:@"CinemaListCell"  owner:self options:nil][0];
                
            }
            cell.backgroundColor = [ UIColor clearColor ];
            [self loadCellData:cell index:indexPath.row];
            break;
        }
        default:
        {
            cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
            // Configure the cell...
            if(cell == nil)
            {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
            }
        }
    }
//    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

//每一个cell定义不同的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0) {
        return TITLECELL_HEIGHT;
    }
    else if (indexPath.section == 1) {
        return MOVIELISTCELL_HEIGHT;
    }
    else{
        return 100;
    }
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 2){
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        if (indexPath.row >= self.cinemaList.count) {
            return;
        }
        
        NSDictionary* dic = self.cinemaList[indexPath.row];
        MovieDetailViewController *movieDetailViewCtrl = [[MovieDetailViewController alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        movieDetailViewCtrl.storeId = [[Common valueForKey:P_ID dic:dic] intValue];
        [self.navigationController pushViewController:movieDetailViewCtrl animated:YES];
        [movieDetailViewCtrl release];
    }
}

#pragma mark - PullTableViewDelegate
- (void)pullTableViewDidTriggerRefresh:(PullTableView*)pullTableView
{
    NSLog(@"refresh...");
//    self.currentIndex = -1;
    //[self getCinemaList];
}

-(void)pullTableViewDidTriggerLoadMore:(PullTableView *)pullTableView
{
    NSLog(@"loadMore...");
    //[self getCinemaList];
}

- (void)resetPullTableViewState
{
    //[self setPullTableIsRefreshing:NO];
    //[self setPullTableIsLoadMore:NO];
}

@end
